package org.hhchat.leetcode.string;

import java.util.Stack;

/**
 * Created this one by HMH on 2017/5/29.
 */
public class code67 {
    public static class Solution {
        public String addBinary(String a, String b) {
            if (a == null || b == null) {
                return "";
            }
            Stack<Integer> vala = new Stack<>();
            Stack<Integer> valb = new Stack<>();
            for (char c : a.toCharArray()) {
                vala.push(c - '0');
            }
            for (char c : b.toCharArray()) {
                valb.push(c - '0');
            }
            int sum=0;
            Stack<Integer> valr = new Stack<>();
            while (!vala.empty() || !valb.empty()) {
                if(!vala.empty()) sum += vala.pop();
                if(!valb.empty()) sum += valb.pop();
                valr.push(sum%2);
                sum /= 2;
            }
            if (sum != 0) {
                valr.push(sum);
            }
            StringBuilder stringBuilder = new StringBuilder();
            while(!valr.empty()) stringBuilder.append(valr.pop());
            return stringBuilder.toString();
        }
    }

    public static void main(String[] args){
        Solution solution = new Solution();
        System.out.println(solution.addBinary("11","1"));
    }
}

//    实际上不需要栈，数组就可以完成。。

//    StringBuilder sb = new StringBuilder();
//    int i = a.length() - 1, j = b.length() -1, carry = 0;
//        while (i >= 0 || j >= 0) {
//                int sum = carry;
//                if (j >= 0) sum += b.charAt(j--) - '0';
//                if (i >= 0) sum += a.charAt(i--) - '0';
//                sb.append(sum % 2);
//                carry = sum / 2;
//                }
//                if (carry != 0) sb.append(carry);
//                return sb.reverse().toString();
